package cn.drenal.gui;

import cn.drenal.common.Constants;
import cn.drenal.common.Main;
import cn.drenal.helper.JDBCHelper;
import cn.drenal.pet.ItemPet;
import sun.jvm.hotspot.ui.table.LongCellRenderer;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.util.ArrayList;

public class GuiList extends PetGui
{
    private ArrayList<ItemPet> listPetPurchased;
    private JTable tableList = new JTable();
    private JScrollPane paneTabelList = new JScrollPane();
    private JPanel panelBtn = new JPanel();
    private JButton btnConfirm = new JButton("确定");
    private JLabel sumLable = new JLabel();

    GuiList(String title, ArrayList<ItemPet> listPetPurchased)
    {
        super(title);
        this.listPetPurchased = listPetPurchased;
    }

    @Override
    public void showGui()
    {
        this.setSize(330, 470);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        this.refreshTableList();
        super.showGui();
    }

    @Override
    protected void addComp()
    {
        DecimalFormat df = new DecimalFormat("#.##");
        double sum = 0;
        this.setLayout(null);
        tableList.getTableHeader().setReorderingAllowed(false);//列不能移动
        tableList.getTableHeader().setResizingAllowed(false);//不可拉动表格
        tableList.setEnabled(false);  //不可更改数据
        tableList.setBounds(0, 0, 160, 400);

        paneTabelList.setBounds(20, 20, 290, 400);
        paneTabelList.add(tableList);
        paneTabelList.setViewportView(tableList);

        for (int i = 0; i < listPetPurchased.size(); i++)
        {
            sum += listPetPurchased.get(i).getPrice() * listPetPurchased.get(i).getQuantity();
        }
        panelBtn.setBounds(0, 400, 330, 30);
        sumLable.setText("共计" + df.format(sum) + "元");
        panelBtn.add(sumLable);
        panelBtn.add(btnConfirm);
        this.add(panelBtn);
        this.add(paneTabelList);
    }

    @Override
    protected void addListener()
    {
        btnConfirm.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                dispose();
            }
        });
    }

    public void refreshTableList()
    {
        for (int i = 0; i < listPetPurchased.size(); i++)
        {
            Main.consoleLog(listPetPurchased.get(i).getBreed());
        }
        //表头
        String[] tabHead = {Constants.BREED_TEXT, Constants.PRICE_TEXT, Constants.QUANTITY_TEXT, "金额"};
        //设置表单体
        String[][] tabBody = JDBCHelper.listToArrayItemPet(listPetPurchased);
        TableModel model = new DefaultTableModel(tabBody, tabHead);
        tableList.setModel(model);
    }
}
